import dov from 'dov-http-mini'
var $ = require('./util.js');
import {config} from './config.js'

class Http {
  constructor (config) {
    this.server = dov.create({
      baseURL: config.baseURL
    })
    this.interceptorsRequest()
    this.responseResponse()
  }
  interceptorsRequest() { // 拦截器
    this.server.interceptors.request.use(function (request) { 
      return request
    })
  }
  responseResponse(){ // 响应器
    this.server.interceptors.response.use(function (response) {
      if (response.statusCode === 200 && response.data.code != 1) {
        return response.data
      } else if (response.statusCode === 200 && response.data.code == 1){ 
        $.toast(response.data.msg)
      }
    })
  }
  // post(url, data={}){
  //   return new Promise((resolve, reject)=>{
  //     this.server.post(url, { data }).then((res) => {
  //       resolve(res)
  //     })
  //   })
  // }
  // get(url, data={}) {
  //   return new Promise((resolve, reject) => {
  //     this.server.get(url, { data }).then((res) => {
  //       resolve(res)
  //     })
  //   })
  // }
  post(url, data = {}) {
    url=config.baseURL+url;
    var user_id = wx.getStorageSync('user_id') || 0
    var data = { ...data, user_id }
    return new Promise((resolve, reject) => {
      wx.request({
        url,
        data,
        method: 'POST',
        header: {
          'dataType': "json",
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        success: (res) => {
          if (res.data.code == 0||res.data.code == -1) { // 成功
            resolve(res.data);
          } else if (res.data.code == 1) { // 错误提示
            $.toast(res.data.msg)
          }else{
            resolve(res.data);
          }

          if (!user_id && url.indexOf('login') == -1) {
            $.linkurl(`/pages/main/login/login`)
          }
        },
        fail: function (res) {
          $.toast('没有网络')
        },
        complete: (t) => {

        },
      })
    })
  }
  get(url, data) {
    url=config.baseURL+url;
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '加载中...',
      });
      wx.request({
        url: url,
        data: data,
        method: 'GET',
        header: {
          'dataType': "json",
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        success: (res) => {
          resolve(res.data);
          wx.hideLoading();

        },
        fail: function (res) {
          reject(res.data)
        }
      })
    })
  }
}

module.exports = new Http(config)